<?php

namespace app\admin\model\user;

use app\admin\model\AuthGroupAccess;
use think\Model;

class UserProposer extends Model
{

    // 表名
    protected $name = 'user_proposer';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'state_text'
    ];
    

    
    public function getStateList()
    {
        return ['-1' => __('State -1'), '0' => __('State 0'), '1' => __('State 1')];
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function setmerchant($ids,$state,$admin_type)
    {   //前置加了进入条件只有一个起作用
        if($state==1){
            $user_find=\app\admin\model\User::where('id',$ids)->where('merchant_state',0)->find();
            $admin_find=\app\admin\model\Admin::where('frontend_user_id',$user_find['id'])->find();

            if($admin_find){
                 \app\admin\model\Admin::where('frontend_user_id',$user_find['id'])->update(['status'=>'normal']);
                 \app\admin\model\User::where('id',$ids)->where('merchant_state',0)->update(['merchant_state'=>1]);
            }else{
                 $admindata=[
                    'username'=>$user_find['username'],
                    'nickname'=>$user_find['nickname'],
                    'password'=>$user_find['password'],
                    'salt'=>$user_find['salt'],
                    'createtime'=>time(),
                    'updatetime'=>time(),
                    'frontend_user_id'=>$user_find['id'],
                 ];

                 $admin_model=new \app\admin\model\Admin;
                 $admin_id=$admin_model::create($admindata)->id;
                 \app\admin\model\User::where('id',$ids)
                     ->where('merchant_state',0)
                     ->update(['merchant_state'=>1,'merchant_id'=>$admin_id]);

                $authgroupdata=[
                    'uid'=>$admin_id,
                    'group_id'=>$admin_type,
                ];
                \app\admin\model\AuthGroupAccess::create($authgroupdata);
            }
        }else{
            \app\admin\model\User::where('id',$ids)->where('merchant_state',1)->update(['merchant_state'=>0]);

            $user_find=\app\admin\model\User::where('id',$ids)->where('merchant_state',0)->find();
            $admin_find=\app\admin\model\Admin::where('frontend_user_id',$user_find['id'])->find();

            if($admin_find){
                \app\admin\model\Admin::where('frontend_user_id',$user_find['id'])->update(['status'=>'hidden']);
            }

        }

    }


}
